package com.bears.god.sup.servlet.operation;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bears.god.sup.model.Dept;
import com.bears.god.sup.service.IdeptService;
import com.bears.god.sup.service.ServiceDAOFactory;

@WebServlet("/editDeptG")
public class EditDeptGServlet extends HttpServlet {
	private static final long serialVersionUID = 123456789L;
	public static final String METHOD_EDIT = "0";
	public static final String METHOD_FINISH = "1";

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		String method = req.getParameter("method");

		if (method != null) {
			switch (method) {
			case EditDeptGServlet.METHOD_EDIT:
				edit(req, resp);
				break;
			case EditDeptGServlet.METHOD_FINISH:
				finish(req, resp);
				break;
			default:
				break;
			}
		}
	}

	private void edit(HttpServletRequest req, HttpServletResponse resp) {
		int id = Integer.parseInt(req.getParameter("id"));
		Dept dept = null;
		try {
			IdeptService ideptService = ServiceDAOFactory.getDeptDAO();
			dept = ideptService.findById(id);
			req.setAttribute("dept", dept);
			req.getRequestDispatcher("WEB-INF/view/cashier/editdeptG.jsp").forward(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void finish(HttpServletRequest req, HttpServletResponse resp) {
		Dept Editdept = new Dept();
		try {

			int id = Integer.parseInt(req.getParameter("id"));
			Editdept.setId(id);
			Editdept.setDepartmentName(req.getParameter("deptName"));
			Editdept.setDescription(req.getParameter("description"));
			IdeptService ideptService = ServiceDAOFactory.getDeptDAO();
			ideptService.update(Editdept);
			req.setAttribute("EditDet_success", "修改成功");
			req.getRequestDispatcher("/deptG?id=1").forward(req, resp);

		} catch (Exception e) {
			e.printStackTrace();
			req.setAttribute("EditDept_err", "修改失败");
			try {
				req.getRequestDispatcher("WEB-INF/view/cashier/editdeptG.jsp").forward(req, resp);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}

}
